package com.flaskpy.web.eternity.auth.jwt.service;

import cn.hutool.core.util.StrUtil;
import com.flaskpy.web.eternity.auth.jwt.entiry.JwtPayLoad;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * jwt 相关userDetail服务
 */
public interface IJwtAuthicationService extends UserDetailsService {

    default JwtPayLoad toJwtContentDTO(Authentication authentication) {

        UserDetails userDetails=(UserDetails) authentication.getPrincipal();
        JwtPayLoad jwtContentDTO=new JwtPayLoad();
        jwtContentDTO.setUserName(userDetails.getUsername());
        jwtContentDTO.setSessionId(StrUtil.uuid());
        jwtContentDTO.setRoleOrAuthorityList(authentication.getAuthorities().stream().map(p->((GrantedAuthority) p).getAuthority()).collect(Collectors.toList()));

        return jwtContentDTO;
    }


    default Authentication toAuthentication(JwtPayLoad jwtContentDTO) {

        List<String> authentications = jwtContentDTO.getRoleOrAuthorityList();
        authentications= authentications==null? Collections.emptyList():authentications;

        List<SimpleGrantedAuthority> grantedAuthoritys = authentications.stream().map(p -> new SimpleGrantedAuthority(p)).collect(Collectors.toList());
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(jwtContentDTO.getUserName(),jwtContentDTO.getSessionId(),grantedAuthoritys);
        return authenticationToken;

    }
//    /**
//     * 转jwtContextDTO  这数据用于登陆后生成的token
//     * @param authentication
//     * @return
//     */
//    JwtPayLoad toJwtContentDTO(Authentication authentication);
//
//    /**
//     * 转Authentication  这数据用于登陆成功给security的 SecurityContext 走流程
//     * @param jwtContentDTO
//     * @return
//     */
//    Authentication toAuthentication(JwtPayLoad jwtContentDTO);

}
